package testmodels

import "github.com/mitchellh/mapstructure"

func (m *SubStruct) update_(n map[string]interface{}, create, record bool) (bool, map[string]interface{}, error) {
	var (
		changed bool                   = false
		oldval  map[string]interface{} = nil
	)
	if record {
		oldval = make(map[string]interface{})
	}
	//[Value] Number,Bool,String; 由:genNormalField 函数生成
	if v, ok := n["age"]; ok {
		if nv, ok := v.(int); ok && nv != m.Age {
			if record {
				oldval["Age"] = m.Age
			}
			m.Age, changed = int(nv), true
		}
	}
	return changed, oldval, nil
}

func (m *SubStruct) Update(n map[string]interface{}) error {
	_, _, err := m.update_(n, false, false)
	return err
}

func (m *SubStruct) UpdateWithCallback(n map[string]interface{}, onchange func(*SubStruct, map[string]interface{})) error {
	changed, oldval, err := m.update_(n, false, true)
	if err != nil {
		return err
	}
	if changed {
		onchange(m, oldval)
	}
	return nil
}

func (m *TestStruct) update_(n map[string]interface{}, create, record bool) (bool, map[string]interface{}, error) {
	var (
		changed bool                   = false
		oldval  map[string]interface{} = nil
	)
	if record {
		oldval = make(map[string]interface{})
	}
	if v, ok := n["sub"]; ok {
		if v == nil {
			if m.Sub != nil {
				if record {
					var o map[string]interface{}
					mapstructure.Decode(m.Sub, &o)
					oldval["Sub"] = o
				}
				m.Sub = nil
				changed = true
			}
		} else {
			if m.Sub == nil {
				m.Sub = &SubStruct{}
			}
			ch, ov, _ := m.Sub.update_(v.(map[string]interface{}), true, record)
			if record && ch {
				oldval["Sub"] = ov
			}
			changed = ch
		}
	}
	return changed, oldval, nil
}

func (m *TestStruct) Update(n map[string]interface{}) error {
	_, _, err := m.update_(n, false, false)
	return err
}

func (m *TestStruct) UpdateWithCallback(n map[string]interface{}, onchange func(*TestStruct, map[string]interface{})) error {
	changed, oldval, err := m.update_(n, false, true)
	if err != nil {
		return err
	}
	if changed {
		onchange(m, oldval)
	}
	return nil
}
